package com.roy.netty.websocket;

import io.netty.channel.Channel;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;

import java.util.concurrent.ConcurrentHashMap;

public class ChannelService {

    private ConcurrentHashMap<String, Channel> allChannel = new ConcurrentHashMap<>();

    public Boolean addChannel(Channel channel){
        Boolean added = false;
        String channelId = channel.id().asLongText();
        if(!allChannel.containsKey(channelId)){
            allChannel.putIfAbsent(channelId,channel);
            added = true;
        }
        return added;
    }

    public void broadCast(TextWebSocketFrame message){
        for (Channel channel : allChannel.values()) {
            channel.writeAndFlush(message);
        }

    }

    public Boolean closeChannel(Channel channel){
        String channelId = channel.id().asLongText();
        Channel c = allChannel.remove(channelId);
        if(null ==c){
            return true;
        }
        return false;
    }
}
